import uuid from 'uuid/v1'

import db from './db.js'
import './dbconfig.js'

function DexieObject (id) {
  var tableName = this.tableName
  this.id = id || `${tableName}_${uuid()}`

  this.init()
}

DexieObject.prototype.tableName = 'DexieObject'

DexieObject.prototype.init = function (isSaved) {
  this._isInited = false
  this._isChanged = false
  this._isSaved = isSaved || false
  this._data = {}
  this._savedDate = {}

  var id = this.id

  Object.defineProperty(this, 'id', {
    value: id,
    writable: false
  })

  this._data.id = id

  for (const key in this) {
    if (this.hasOwnProperty(key) && !key.startsWith('_') && key !== 'id') {
      this._data[key] = this[key]
      this._savedDate[key] = this[key]

      Object.defineProperty(this, key, {
        get: function () {
          return this._data[key]
        },
        set: function (newValue) {
          if (this._data[key] !== newValue) {
            this._isChanged = true
          }
          this._data[key] = newValue
        },
        enumerable: true,
        configurable: true
      })
    }
  }

  this._isInited = true
}

DexieObject.prototype.save = function () {
  var tableName = this.tableName
  if (!this._isSaved) {
    return db[tableName].add(this._data).then(result => {
      this._isSaved = true
      this._isChanged = false
      return result
    })
  } else {
    return db[tableName].update(this.id, this._data).then(result => {
      this._isChanged = false
      return result
    })
  }
}

DexieObject.prototype.reset = function () {

}

DexieObject.prototype.update = function () {

}

DexieObject.prototype.delete = function () {
  var tableName = this.tableName
  return db[tableName].delete(this.id)
}

export default DexieObject
